package com.lw.leetcode.stack.c;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Stack;

/**
 * Created with IntelliJ IDEA.
 * 6019. 替换数组中的非互质数
 *
 * @author liw
 * @version 1.0
 * @date 2022/3/6 20:39
 */
public class ReplaceNonCoprimes {

    public List<Integer> replaceNonCoprimes(int[] nums) {
        Stack<Integer> stack = new Stack<>();
        for (int num : nums) {
            while (true) {
                if (stack.isEmpty()) {
                    break;
                }
                int g = find(num, stack.peek());
                if (g == 1) {
                    break;
                }
                num = (int) ((long) stack.pop() * num / g);
            }
            stack.add(num);
        }
        List<Integer> list = new ArrayList<>(stack.size());
        while (!stack.isEmpty()) {
            list.add(stack.pop());
        }
        Collections.reverse(list);
        return list;
    }

    private int find(int a, int b) {
        return b == 0 ? a : find(b, a % b);
    }

}
